﻿
using SqlSugar;
using System.Linq;

namespace Finance.Infrastructure
{
    public class SqlsugarDb<T>  where T : class,new()
    {
        private readonly ISqlSugarClient db;

        public SqlsugarDb(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T t)
        { 
        var result=await db.Insertable(t).ExecuteCommandAsync();
            return result;
            
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> Updata(T t)
        { 
        return await db.Updateable(t).ExecuteCommandAsync();
           
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(T entity)
        {
          return await db.Deleteable(entity).ExecuteCommandAsync();
           
        }
        //单查询
        public ISugarQueryable<T> FirstQuery()
        {

            return  db.Queryable<T>();

        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public async Task<int> Addlist(List<T> entity)
        {
            if (entity == null || entity.Count == 0)
            {
                throw new ArgumentNullException("实体列表不能为空");
            }
            return await db.Insertable(entity).ExecuteCommandAsync();
        }

        /// <summary>
        /// 事务封装
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task<int> BeginTransaction(Func<Task<int>> action)
        {
            int res = 0;
            try
            {
               db.Ado.BeginTran();
                res = await action();
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                await db.Ado.RollbackTranAsync();
                throw ex;
            }
            return res;
        }


        public async Task<int> AddReturnId(T t)
        { 
        
            return await db.Insertable(t).ExecuteReturnIdentityAsync();
        }

    }
}
